// background.js - Service Worker for Chrome Extension
class APIInterceptor {
  constructor() {
    this.rules = new Map();
    this.tabRequestRecords = new Map();
    this.init();
  }

  async init() {
    // 加载存储的拦截规则
    await this.loadRules();
    
    // 监听webRequest事件
    this.setupWebRequestListeners();
    
    // 监听来自DevTools Panel的消息
    this.setupMessageListeners();
  }

  async loadRules() {
    try {
      const result = await chrome.storage.local.get(['interceptRules']);
      if (result.interceptRules) {
        this.rules = new Map(Object.entries(result.interceptRules));
      }
    } catch (error) {
      // 静默处理加载失败，可能是首次运行或storage不可用
    }
  }

  async saveRules() {
    try {
      const rulesObj = Object.fromEntries(this.rules);
      await chrome.storage.local.set({ interceptRules: rulesObj });
    } catch (error) {
      // 静默处理保存失败
    }
  }

  setupWebRequestListeners() {
    // 监听请求前事件 - 记录和修改请求数据
    chrome.webRequest.onBeforeRequest.addListener(
      (details) => {
        this.recordRequest(details);
        return this.handleBeforeRequest(details);
      },
      { urls: ['<all_urls>'] },
      ['requestBody']
    );

    // 监听请求头 - 用于修改请求头
    chrome.webRequest.onBeforeSendHeaders.addListener(
      (details) => this.handleBeforeSendHeaders(details),
      { urls: ['<all_urls>'] },
      ['requestHeaders']
    );

    // 监听响应头 - 用于修改响应头
    chrome.webRequest.onHeadersReceived.addListener(
      (details) => this.handleHeadersReceived(details),
      { urls: ['<all_urls>'] },
      ['responseHeaders']
    );

    // 监听响应完成 - 记录响应数据
    chrome.webRequest.onCompleted.addListener(
      (details) => this.recordResponse(details),
      { urls: ['<all_urls>'] }
    );
  }

  recordRequest(details) {
    // 过滤掉扩展自身的请求
    if (details.initiator === `chrome-extension://${chrome.runtime.id}`) {
      return;
    }

    // 只记录HTTP/HTTPS的API请求
    if (!details.url.startsWith('http')) {
      return;
    }

    // 过滤只抓取API请求类型，排除静态资源
    const url = details.url.toLowerCase();
    
    // 排除静态资源文件
    if (url.match(/\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|mp4|mp3|pdf|zip)(\?.*)?$/)) {
      return;
    }
    
    // 排除一些明显的非API请求
    if (url.includes('google-analytics') || 
        url.includes('googletagmanager') || 
        url.includes('facebook.com') ||
        url.includes('doubleclick.net') ||
        url.includes('googlesyndication') ||
        url.includes('.js.map') ||
        url.includes('chrome-extension://')) {
      return;
    }
    
    // 主要关注可能是API的请求：包含api、service、data等关键词的URL，或者是POST/PUT/DELETE请求
    const method = details.method.toUpperCase();
    const isApiUrl = url.includes('/api/') || 
                     url.includes('/service/') || 
                     url.includes('/data/') ||
                     url.includes('/v1/') ||
                     url.includes('/v2/') ||
                     url.includes('.json') ||
                     url.includes('/ajax/') ||
                     url.includes('/graphql');
    
    const isApiMethod = method === 'POST' || method === 'PUT' || method === 'DELETE' || method === 'PATCH';
    
    // 如果不是明显的API请求，则跳过
    if (!isApiUrl && !isApiMethod && method === 'GET') {
      return;
    }

    const requestId = details.requestId;
    const tabId = details.tabId;
    
    if (tabId && tabId > 0) {
      if (!this.tabRequestRecords.has(tabId)) {
        this.tabRequestRecords.set(tabId, {});
      }

      const requestRecord = {
        id: `${requestId}_${Date.now()}`,
        url: details.url,
        method: details.method.toUpperCase(),
        requestHeaders: {},
        requestBody: null,
        responseHeaders: {},
        responseBody: null,
        status: 0,
        timestamp: Date.now()
      };

      // 尝试解析请求体
      if (details.requestBody) {
        try {
          if (details.requestBody.raw) {
            const decoder = new TextDecoder();
            const bodyText = decoder.decode(details.requestBody.raw[0].bytes);
            requestRecord.requestBody = JSON.parse(bodyText);
          } else if (details.requestBody.formData) {
            requestRecord.requestBody = details.requestBody.formData;
          }
        } catch (error) {
          // 静默处理解析失败
        }
      }

      const tabRequests = this.tabRequestRecords.get(tabId);
      tabRequests[requestRecord.id] = requestRecord;

      // 限制记录数量
      const requestIds = Object.keys(tabRequests);
      if (requestIds.length > 50) {
        const sortedIds = requestIds.sort((a, b) => {
          return (tabRequests[a].timestamp || 0) - (tabRequests[b].timestamp || 0);
        });
        const oldestId = sortedIds[0];
        delete tabRequests[oldestId];
      }
    }
  }

  recordResponse(details) {
    const tabId = details.tabId;
    const requestId = details.requestId;
    
    if (tabId && tabId > 0) {
      const tabRequests = this.tabRequestRecords.get(tabId);
      if (tabRequests) {
        // 查找对应的请求记录并更新状态码
        for (const record of Object.values(tabRequests)) {
          if (record.id.includes(requestId)) {
            record.status = details.statusCode;
            break;
          }
        }
      }
    }
  }

  setupMessageListeners() {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      // 重要：使用异步处理并确保调用sendResponse
      this.handleMessage(message, sender, sendResponse);
      
      // 返回true表示异步处理消息
      return true;
    });
  }

  handleBeforeRequest(details) {
    const rule = this.findMatchingRule(details.url, details.method);
    if (!rule || !rule.enabled) return;

    // 如果有自定义请求体，则修改请求
    if (rule.requestModification && rule.requestModification.body) {
      try {
        const modifiedBody = JSON.stringify(rule.requestModification.body);
        return {
          requestBody: {
            raw: [{
              bytes: new TextEncoder().encode(modifiedBody)
            }]
          }
        };
      } catch (error) {
        console.error('修改请求体失败:', error);
      }
    }
  }

  handleBeforeSendHeaders(details) {
    const rule = this.findMatchingRule(details.url, details.method);
    if (!rule || !rule.enabled) return;

    let headers = details.requestHeaders || [];

    // 修改请求头
    if (rule.requestModification && rule.requestModification.headers) {
      Object.entries(rule.requestModification.headers).forEach(([name, value]) => {
        const existingHeader = headers.find(h => h.name.toLowerCase() === name.toLowerCase());
        if (existingHeader) {
          existingHeader.value = value;
        } else {
          headers.push({ name, value });
        }
      });
    }

    return { requestHeaders: headers };
  }

  handleHeadersReceived(details) {
    const rule = this.findMatchingRule(details.url, details.method);
    if (!rule || !rule.enabled) return;

    let headers = details.responseHeaders || [];

    // 如果需要返回mock数据，注入内容脚本
    if (rule.responseModification && rule.responseModification.body) {
      this.injectResponseModification(details.tabId, details.url, rule.responseModification);
    }

    // 修改响应头
    if (rule.responseModification && rule.responseModification.headers) {
      Object.entries(rule.responseModification.headers).forEach(([name, value]) => {
        const existingHeader = headers.find(h => h.name.toLowerCase() === name.toLowerCase());
        if (existingHeader) {
          existingHeader.value = value;
        } else {
          headers.push({ name, value });
        }
      });
    }

    return { responseHeaders: headers };
  }

  async injectResponseModification(tabId, url, responseModification) {
    try {
      await chrome.scripting.executeScript({
        target: { tabId },
        func: this.injectResponseHandler,
        args: [url, responseModification]
      });
    } catch (error) {
      console.error('注入响应修改脚本失败:', error);
    }
  }

  // 这个函数会被注入到页面中
  injectResponseHandler(url, responseModification) {
    // 创建一个自定义事件来通知content script
    const event = new CustomEvent('apiMockResponse', {
      detail: { url, responseModification }
    });
    document.dispatchEvent(event);
  }

  findMatchingRule(url, method) {
    for (const [ruleId, rule] of this.rules) {
      if (this.urlMatches(url, rule.urlPattern) && 
          (!rule.method || rule.method === method)) {
        return rule;
      }
    }
    return null;
  }

  urlMatches(url, pattern) {
    try {
      // 支持正则表达式和简单的字符串匹配
      if (pattern.startsWith('/') && pattern.endsWith('/')) {
        const regex = new RegExp(pattern.slice(1, -1));
        return regex.test(url);
      } else {
        return url.includes(pattern);
      }
    } catch (error) {
      console.error('URL匹配失败:', error);
      return false;
    }
  }

  async handleMessage(message, sender, sendResponse) {
    try {
      switch (message.type) {
        case 'GET_RULES':
          sendResponse({
            success: true,
            data: Object.fromEntries(this.rules)
          });
          break;

        case 'GET_PAGE_REQUESTS':
          const tabId = message.tabId || sender.tab?.id;
          
          if (tabId) {
            // 先尝试从background存储中获取
            const requests = this.tabRequestRecords.get(tabId) || {};
            
            // 如果background中没有，尝试从content script获取
            if (Object.keys(requests).length === 0) {
              try {
                const response = await chrome.tabs.sendMessage(tabId, {
                  type: 'GET_REQUEST_RECORDS'
                });
                if (response && response.success) {
                  sendResponse({
                    success: true,
                    data: response.data
                  });
                  return; // 重要：确保只调用一次sendResponse
                }
              } catch (error) {
                // 静默处理从content script获取失败
              }
            }
            
            sendResponse({
              success: true,
              data: requests
            });
          } else {
            sendResponse({
              success: false,
              error: '无法获取标签页ID'
            });
          }
          break;

        case 'NEW_REQUEST_RECORD':
          const recordTabId = message.tabId || sender.tab?.id;
          
          if (recordTabId && message.record) {
            if (!this.tabRequestRecords.has(recordTabId)) {
              this.tabRequestRecords.set(recordTabId, {});
            }
            
            const tabRequests = this.tabRequestRecords.get(recordTabId);
            tabRequests[message.record.id] = message.record;
            
            // 限制每个标签页最多保存50个请求记录
            const requestIds = Object.keys(tabRequests);
            if (requestIds.length > 50) {
              // 按时间戳排序，删除最旧的记录
              const sortedIds = requestIds.sort((a, b) => {
                return (tabRequests[a].timestamp || 0) - (tabRequests[b].timestamp || 0);
              });
              const oldestId = sortedIds[0];
              delete tabRequests[oldestId];
            }
            
            sendResponse({ success: true });
          } else {
            sendResponse({ success: false, error: '缺少必要参数' });
          }
          break;

        case 'ADD_RULE':
          const ruleId = Date.now().toString();
          this.rules.set(ruleId, { ...message.rule, id: ruleId });
          await this.saveRules();
          sendResponse({ success: true, ruleId });
          break;

        case 'UPDATE_RULE':
          if (this.rules.has(message.ruleId)) {
            this.rules.set(message.ruleId, { ...message.rule, id: message.ruleId });
            await this.saveRules();
            sendResponse({ success: true });
          } else {
            sendResponse({ success: false, error: '规则不存在' });
          }
          break;

        case 'DELETE_RULE':
          if (this.rules.delete(message.ruleId)) {
            await this.saveRules();
            sendResponse({ success: true });
          } else {
            sendResponse({ success: false, error: '规则不存在' });
          }
          break;

        case 'TOGGLE_RULE':
          const rule = this.rules.get(message.ruleId);
          if (rule) {
            rule.enabled = !rule.enabled;
            await this.saveRules();
            sendResponse({ success: true, enabled: rule.enabled });
          } else {
            sendResponse({ success: false, error: '规则不存在' });
          }
          break;

        default:
          sendResponse({ success: false, error: '未知消息类型' });
      }
    } catch (error) {
      sendResponse({ success: false, error: error.message });
    }
  }
}

// 启动拦截器
const interceptor = new APIInterceptor();